package com.calendar.add;

import java.util.Calendar;

import com.calendar.day.DayView;
import com.calendar.widget.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.net.Uri.Builder;
import android.os.Bundle;
import android.text.format.Time;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TimePicker;

//TODO add full day. 
// add status
// add visibility
// add alarm

public class AddView extends Activity {

	long start, end;
	String name, location, Description, attenString, attendees[];
	int starthour, startmin, startyear, startmonth, startday;
	int endhour, endmin, endyear, endmonth, endday;
	int eventid;
	EditText nameText;
	EditText locationText;
	EditText attendeesText;
	EditText descriptionText;
	Spinner spin;
	Button cancel, done, delete;
	Button startdate, enddate, starttime, endtime;
	boolean edit = false;
	String[] cal;
	Calendar cale;

	int dayValue;
	int monthValue;
	int yearValue;

	Uri remindersUri;
	Uri eventsUri;
	Uri calendars;

	static final int START_TIME_DIALOG_ID = 0;
	static final int START_DATE_DIALOG_ID = 1;
	static final int END_TIME_DIALOG_ID = 2;
	static final int END_DATE_DIALOG_ID = 3;

	/** Called when the activity is first created. */
	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_view);
		nameText = (EditText) findViewById(R.id.EditText01);
		locationText = (EditText) findViewById(R.id.EditText02);
		attendeesText = (EditText) findViewById(R.id.EditText03);
		descriptionText = (EditText) findViewById(R.id.EditText04);
		spin = (Spinner) findViewById(R.id.Spinner01);
		cancel = (Button) findViewById(R.id.Cancel);
		startdate = (Button) findViewById(R.id.StartDate);
		starttime = (Button) findViewById(R.id.StartTime);
		enddate = (Button) findViewById(R.id.EndDate);
		endtime = (Button) findViewById(R.id.EndTime);
		done = (Button) findViewById(R.id.Done);
		delete = (Button) findViewById(R.id.Delete);

		cale = Calendar.getInstance();

		ArrayAdapter<CharSequence> spinAdapt = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item);
		spinAdapt.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spin.setAdapter(spinAdapt);

		Bundle extras = getIntent().getExtras();
		if(getIntent().getAction() == null && extras != null){
			dayValue = extras.getInt("day");
			monthValue = extras.getInt("month");
			yearValue = extras.getInt("year");
			eventid=Integer.parseInt(extras.getString("eventID"));
			edit=true;
		}
		else if (extras != null && !getIntent().getAction().contains("Add")) {
			dayValue = extras.getInt("day");
			monthValue = extras.getInt("month");
			yearValue = extras.getInt("year");
			eventid=Integer.parseInt(extras.getString("eventID"));
			edit=true;
		}

		//db stuff
		String contentProvider;
		String[] projection = new String[] {"_id","name" };

		if(android.os.Build.VERSION.SDK_INT > 7)
			contentProvider = "com.android.calendar";
		else
			contentProvider = "calendar";

		remindersUri = Uri.parse(String.format("content://%s/reminders",contentProvider));
		eventsUri = Uri.parse(String.format("content://%s/events",contentProvider));
		calendars = Uri.parse(String.format("content://%s/calendars",contentProvider));

		//get and parse results. 
		Cursor managedcursor = managedQuery(calendars,projection,null,null,null);
		cal = new String[managedcursor.getCount()];
		int pos = 0;

		if(managedcursor.moveToFirst()){
			int nameColumn = managedcursor.getColumnIndex("name");
			int idColumn = managedcursor.getColumnIndex("_id");
			do{
				cal[pos] = managedcursor.getString(nameColumn)+ "," + managedcursor.getString(idColumn);
				pos = pos+1;
			} while (managedcursor.moveToNext());
		}
		for(int i = 0; i < cal.length; i++){
			spinAdapt.add(cal[i]);
		}

		if(edit){
			projection = new String[] {"calendar_id", "title", "description","eventLocation","dtstart","dtend"};
			managedcursor = managedQuery(eventsUri,projection,"_id="+eventid,null,null);
			managedcursor.moveToFirst();
			name = managedcursor.getString(managedcursor.getColumnIndex("title"));
			location = managedcursor.getString(managedcursor.getColumnIndex("eventLocation"));
			Description = managedcursor.getString(managedcursor.getColumnIndex("description"));
			start = managedcursor.getLong(managedcursor.getColumnIndex("dtstart"));
			end = managedcursor.getLong(managedcursor.getColumnIndex("dtend"));
			spin.setSelection(managedcursor.getInt(managedcursor.getColumnIndex("calendar_id")) - 1);

			nameText.setText(name);
			locationText.setText(location);
			descriptionText.setText(Description);

			Time t = new Time();
			t.set(start);
			startdate.setText((t.month+1) + "/" + t.monthDay + "/" + t.year);
			if(t.minute >= 10) starttime.setText(t.hour+":"+t.minute);
			else starttime.setText(t.hour+":0"+t.minute);
			startyear = t.year;
			startmonth = t.month;
			startday = t.monthDay;
			starthour = t.hour;
			startmin = t.minute;
			t.set(end);
			enddate.setText((t.month+1)+"/"+t.monthDay + "/" + t.year);
			if(t.minute >= 10) endtime.setText(t.hour+":"+t.minute);
			else endtime.setText(t.hour+":0"+t.minute);
			endyear = t.year;
			endmonth = t.month;
			endday = t.monthDay;
			endhour = t.hour;
			endmin = t.minute;
		}
		else{
			Time t = new Time();
			t.setToNow();
			startdate.setText((t.month+1) + "/" + t.monthDay + "/" + t.year);
			if(t.minute >= 10) starttime.setText(t.hour+":"+t.minute);
			else starttime.setText(t.hour+":0"+t.minute);
			startyear = t.year;
			startmonth = t.month;
			startday = t.monthDay;
			starthour = t.hour;
			startmin = t.minute;
			t.hour = t.hour+1;
			enddate.setText((t.month+1)+"/"+t.monthDay + "/" + t.year);
			if(t.minute >= 10) endtime.setText(t.hour+":"+t.minute);
			else endtime.setText(t.hour+":0"+t.minute);
			endyear = t.year;
			endmonth = t.month;
			endday = t.monthDay;
			endhour = t.hour;
			endmin = t.minute;
		}

		//button done config
		done.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				name = nameText.getText().toString().trim();
				location = locationText.getText().toString().trim();
				Description = descriptionText.getText().toString().trim();
				attenString = attendeesText.getText().toString().trim();
				attendees = attenString.split("[ ,]");
				Time t = new Time();
				t.hour=starthour;
				t.minute=startmin;
				t.year=startyear;
				t.month=startmonth;
				t.monthDay=startday;
				start = t.toMillis(false);
				t.hour=endhour;
				t.minute=endmin;
				t.year=endyear;
				t.monthDay=endmonth;
				t.monthDay=endday;
				end = t.toMillis(false);

				if(edit){
					ContentValues values = new ContentValues();
					values.put("title",name);
					values.put("description", Description);
					values.put("eventLocation",location);
					values.put("calendar_id",spin.getSelectedItemPosition() + 1);
					values.put("dtstart", start);
					values.put("dtend",end);
					Builder b = eventsUri.buildUpon();
					b.appendEncodedPath("/" + eventid);
					getContentResolver().update(b.build(), values, null, null);

					Intent myIntent = new Intent(getBaseContext(), DayView.class);
					myIntent.putExtra("day", dayValue);
					myIntent.putExtra("month", monthValue);
					myIntent.putExtra("year", yearValue);
					startActivityForResult(myIntent, 0);
					finish();
				} else {
					ContentValues event = new ContentValues();
					event.put("calendar_id", spin.getSelectedItemPosition() + 1);
					event.put("title", name);
					event.put("description", Description);
					event.put("eventLocation", location);
					event.put("dtstart", start);
					event.put("dtend", end);
					getContentResolver().insert(eventsUri, event);

					Intent myIntent = new Intent(getBaseContext(), DayView.class);
					myIntent.putExtra("day", startday);
					myIntent.putExtra("month", startmonth);
					myIntent.putExtra("year", startyear);
					startActivityForResult(myIntent, 0);
					finish();
				}
			}
		});

		// button cancel config
		cancel.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				if(edit){
					Intent myIntent = new Intent(getBaseContext(), DayView.class);
					myIntent.putExtra("day", dayValue);
					myIntent.putExtra("month", monthValue);
					myIntent.putExtra("year", yearValue);
					startActivityForResult(myIntent, 0);
					finish();
				}
				else{
					Intent myIntent = new Intent(getBaseContext(), DayView.class);
					myIntent.putExtra("day", startday);
					myIntent.putExtra("month", startmonth);
					myIntent.putExtra("year", startyear);
					startActivityForResult(myIntent, 0);
					finish();
				}
			}
		});

		//Button delete config
		delete.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				confirmDeleteAlert();
			}
		});
		startdate.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				showDialog(START_DATE_DIALOG_ID);
			}
		});
		enddate.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				showDialog(END_DATE_DIALOG_ID);
			}
		});
		starttime.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				showDialog(START_TIME_DIALOG_ID);
			}
		});
		endtime.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				showDialog(END_TIME_DIALOG_ID);
			}
		});
	}

	private void confirmDeleteAlert() {
		new AlertDialog.Builder(this)
		.setTitle("Delete?")
		.setMessage("Are you sure want to delete this event?")
		.setPositiveButton("Yes",
				new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dlg, int which) {
				Builder b = eventsUri.buildUpon();
				b.appendEncodedPath("/" + eventid);
				getContentResolver().delete(b.build(), null, null);
				if(edit){
					Intent myIntent = new Intent(getBaseContext(), DayView.class);
					myIntent.putExtra("day", dayValue);
					myIntent.putExtra("month", monthValue);
					myIntent.putExtra("year", yearValue);
					startActivityForResult(myIntent, 0);
					finish(); 
				}
				else{
					Intent myIntent = new Intent(getBaseContext(), DayView.class);
					myIntent.putExtra("day", startday);
					myIntent.putExtra("month", startmonth);
					myIntent.putExtra("year", startyear);
					startActivityForResult(myIntent, 0);
					finish();
				}
			}
		})
		.setNegativeButton("No", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface arg0, int arg1) {
				arg0.cancel();
			}
		}).show();
	}

	protected void onSaveInstanceState(Bundle savedInstanceState){
		//take values from inputs
		name = nameText.getText().toString().trim();
		location = locationText.getText().toString().trim();
		Description = descriptionText.getText().toString().trim();
		attenString = attendeesText.getText().toString().trim();
		attendees = attenString.split("[ ,]");

		Time t = new Time();
		t.hour=starthour;
		t.minute=startmin;
		t.year=startyear;
		t.month=startmonth;
		t.monthDay=startday;
		start = t.toMillis(false);
		t.hour=endhour;
		t.minute=endmin;
		t.year=endyear;
		t.monthDay=endmonth;
		t.monthDay=endday;
		end = t.toMillis(false);

		//save inputs to instance state
		savedInstanceState.putLong("start", start);
		savedInstanceState.putLong("end", end);
		savedInstanceState.putString("name", name);
		savedInstanceState.putString("location",location);
		savedInstanceState.putString("Description",Description);
		savedInstanceState.putStringArray("attendees", attendees);
	}

	public void onBackPressed(){
		if(edit){
			Intent myIntent = new Intent(getBaseContext(), DayView.class);
			myIntent.putExtra("day", dayValue);
			myIntent.putExtra("month", monthValue);
			myIntent.putExtra("year", yearValue);
			startActivityForResult(myIntent, 0);
			finish(); 
		}
		else{
			Intent myIntent = new Intent(getBaseContext(), DayView.class);
			myIntent.putExtra("day", startday);
			myIntent.putExtra("month", startmonth);
			myIntent.putExtra("year", startyear);
			startActivityForResult(myIntent, 0);
			finish();
		}
	}

	protected void onRestoreInstanceState(Bundle savedInstanceState){
		super.onRestoreInstanceState(savedInstanceState);
		start = savedInstanceState.getLong("start");
		end = savedInstanceState.getLong("end");
		name = savedInstanceState.getString("name");
		location = savedInstanceState.getString("location");
		Description = savedInstanceState.getString("Description");
		attendees = savedInstanceState.getStringArray("attendees");

		nameText.setText(name);
		locationText.setText(location);
		descriptionText.setText(Description);
		attenString="";
		for(int i=0;i==attendees.length;i++){
			attenString=attenString + "," + attendees[i];
		}
		attendeesText.setText(attenString);

		Time t = new Time();
		t.set(start);
		startmin = t.minute;
		starthour = t.hour;
		startday = t.monthDay;
		startmonth = t.month;
		startyear = t.year;
		t.set(end);
		endmin = t.minute;
		endhour = t.hour;
		endday = t.monthDay;
		endmonth = t.month;
		endyear = t.year;
	}

	protected Dialog onCreateDialog(int id){
		switch(id){
		case START_TIME_DIALOG_ID:
			return new TimePickerDialog(this, StartTimeListener, starthour, startmin, false);
		case START_DATE_DIALOG_ID:
			return new DatePickerDialog(this, StartDateListener, startyear, startmonth, startday);
		case END_TIME_DIALOG_ID:
			return new TimePickerDialog(this, EndTimeListener, endhour, endmin, false);
		case END_DATE_DIALOG_ID:
			return new DatePickerDialog(this, EndDateListener, endyear, endmonth, endday);
		}
		return null;
	}

	private TimePickerDialog.OnTimeSetListener StartTimeListener = new TimePickerDialog.OnTimeSetListener() {

		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			starthour = hourOfDay;
			startmin = minute;
			if(startmin>10)
				starttime.setText(starthour+":"+startmin);
			else 
				starttime.setText(starthour+":0"+startmin);
			endhour = starthour + 1;
			endmin = startmin;
			if (endmin > 10)
				endtime.setText(endhour + ":" + endmin);
			else
				endtime.setText(endhour + ":0" + endmin);
		}
	};

	private TimePickerDialog.OnTimeSetListener EndTimeListener = new TimePickerDialog.OnTimeSetListener() {

		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			endhour = hourOfDay;
			endmin = minute;
			if(endmin>10)
				endtime.setText(endhour+":"+endmin);
			else 
				endtime.setText(endhour+":0"+endmin);
		}
	};

	private DatePickerDialog.OnDateSetListener StartDateListener = new DatePickerDialog.OnDateSetListener() {

		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			startyear=year;
			startmonth=monthOfYear;
			startday=dayOfMonth;
			startdate.setText((startmonth+1) +"/"+startday+"/"+startyear);
			endyear = startyear;
			endmonth = startmonth;
			endday = startday;
			enddate.setText((endmonth + 1) + "/" + endday + "/" + endyear);

		}
	};

	private DatePickerDialog.OnDateSetListener EndDateListener = new DatePickerDialog.OnDateSetListener() {

		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			endyear=year;
			endmonth=monthOfYear;
			endday=dayOfMonth;
			enddate.setText((endmonth+1)+"/"+endday+"/"+endyear);
			
		}
	};
}